package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 根据时间区间统计营业额
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询营业额
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            //处理为空的数据
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 统计用户
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUser = userMapper.getUserCount(beginTime, endTime);
            Integer totalUser = userMapper.getUserCount(null, endTime);


            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        Double orderCompletionRate = 0.0;
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = orderMapper.getOrderCount(beginTime, endTime, null);
            orderCountList.add(orderCount);
            Integer validCount = orderMapper.getOrderCount(beginTime, endTime, Orders.COMPLETED);
            validOrderCountList.add(validCount);
            totalOrderCount += orderCount;
            validOrderCount += validCount;
        }

        if (totalOrderCount != null) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .build();
    }

    /**
     * 销量排名统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        Map map = new HashMap();
        map.put("status", Orders.COMPLETED);
        map.put("begin", beginTime);
        map.put("end", endTime);

        List<GoodsSalesDTO> goodsSalesDTOS = orderDetailMapper.getNameAndNumber(map);
        goodsSalesDTOS.forEach(goodsSalesDTO -> {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        });

//        nameList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
//        numberList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }


    /**
     * 借用POI导出数据
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        try {
            LocalDate now = LocalDate.now();
            LocalDateTime begin = LocalDateTime.of(now.minusDays(30), LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(now.minusDays(1), LocalTime.MAX);
            //0.获取近30的概览数据
            BusinessDataVO totalBusinessDate = workspaceService.getBusinessData(begin, end);

            //1.获取近30天的明细数据
            List<LocalDate> localDates = getLocalDates(now.minusDays(30), now.minusDays(1));

            //2.基于模板工作簿对象
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(is);

            //3.获取工作表对象
            XSSFSheet sheet = excel.getSheetAt(0);

            //4.获取指定的一些行对象，以便获取单元格
            //4.1 设置概览数据
            sheet.getRow(1).getCell(1).setCellValue("时间：" + now.minusDays(30) + "至" + now.minusDays(1));
            sheet.getRow(3).getCell(2).setCellValue(totalBusinessDate.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(totalBusinessDate.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(totalBusinessDate.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(totalBusinessDate.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(totalBusinessDate.getUnitPrice());

            //4.2 设置明细数据
            List<BusinessDataVO> businessDataVOS = new ArrayList<>();
            /*localDates.forEach(data -> {
                sheet.getRow(7).getCell(1).setCellValue(data);
            });*/

            int row = 7;
            for (LocalDate date : localDates) {
                log.info("时间：{}",date);
                sheet.getRow(row).getCell(1).setCellValue(date.toString());
                LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
                BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
                sheet.getRow(row).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(row).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(row).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(row).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(row).getCell(6).setCellValue(businessData.getNewUsers());
                row++;
            }
            //5.将内存中的文件以文件流的方式下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //6.关闭资源
            out.flush();
            out.close();
            excel.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }


    /**
     * 抽取的获取时间列表的方法
     *
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
